package ch.cryptobox.encryption;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.crypto.spec.SecretKeySpec;

import ch.cryptobox.Globals;

public class KeyManager {

	private static final SimpleDateFormat formatter=new SimpleDateFormat("yyyy MM dd HH:mm");
	private static KeyManager instance;
	private static String path;
	private final File keyFolder;

	public static void initInstance(final String path) {
		instance = new KeyManager(path);
	}

	public static KeyManager getInstance()
	{
		if(instance==null)
			instance=new KeyManager(Globals.DEFAULT_KEYS_PATH);

		return instance;
	}

	private KeyManager(final String keysPath)
	{
		path = keysPath;
		keyFolder=new File(path);
		if(!keyFolder.exists())
			keyFolder.mkdir();
	}

	public void storeKey(final SecretKeySpec skeySpec, final int id)
	{
		final String name="key_"+id+"_"+formatter.format(new Date());
		final File f=new File(path+File.separator+name);

		try {
			if(f.createNewFile())
			{
				final ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(f));
				oos.writeObject(skeySpec);
				oos.close();
			}
		} catch (final IOException e) {
			e.printStackTrace();
		}
	}

	public SecretKeySpec getKey(final Date fileDate, final int id)
	{

		String current="";
		Date currentDate=null;//new Date();
		try {
			final Date date=formatter.parse(formatter.format(fileDate));
			for(final String s: keyFolder.list())
			{
				final String[] split=s.split("_");
				final int currentId=Integer.parseInt(split[1]);

				if(id!=currentId) continue;

				final Date d = formatter.parse(split[2]);
				if((d.before(date) || d.equals(date) ) && (currentDate==null || d.after(currentDate)))
				{
					current=s;
					currentDate=d;
				}
			}

			if(currentDate==null) 
				current=keyFolder.list()[0];

			final ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File(keyFolder.getAbsolutePath()+File.separator+current)));
			final SecretKeySpec key=(SecretKeySpec) ois.readObject();
			return key;
		} catch (ParseException | IOException | ClassNotFoundException e) {
			e.printStackTrace();
		}

		return null;
	}

	public SecretKeySpec getKeyForNow(final int id) {

		try {
			final String name="key_"+id+"_"+formatter.format(new Date());
			final File f=new File(path+File.separator+name); 

			if(f.exists())
			{
				final ObjectInputStream ois=new ObjectInputStream(new FileInputStream(f));
				final SecretKeySpec key=(SecretKeySpec) ois.readObject();
				return key;
			}

		} catch (IOException | ClassNotFoundException e) {
			e.printStackTrace();
		}

		return null;
	}

}
